package com.mrper.ui.brand;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguo.activity.callback.IGoodsScroll;
import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.app.AppHelper;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.pulltorefresh.PullToRefreshBase;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentBrandDetailListcontentBinding;
import com.miguo.ui.databinding.GriditemBrandDetailBinding;
import com.mrper.ext.adapter.TempleteAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.event.BrandDetailGoodsListViewScrollStateChangedEvent;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.ext.widget.BrandSortView;
import com.mrper.model.entry.brand.BrandDetailListInfoEntry;
import com.mrper.util.AnimationUtil;
import com.mrper.util.DensityUtil;
import com.mrper.util.DeviceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/23.
 * 品牌内页列表内容
 */
@ContentView(R.layout.fragment_brand_detail_listcontent)
public class FragmentBrandDetailListContent extends BasicFragment<FragmentBrandDetailListcontentBinding>
        implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListenerTwo<GridView>, IGoodsScroll, View.OnClickListener {

    private TempleteAdapter<GriditemBrandDetailBinding, BrandDetailListInfoEntry> adapter;//数据适配器
    private boolean isHadLoaded = false;//是否已经加载过一次了
    private int brandThemeId = -1; // 品牌主题ID
    private int currentPage = 0, pageCount = 0, lastVisibleItemIndex = 0;//当前页码,上一次可见的列表项索引
    private int sort = BrandSortView.SORT_DEFAULT, sortMode = BrandSortView.MODE_NONE;//排序变量
    private String sortState = "";//默认排序

    @Override
    protected void initViews() {
        super.initViews();
        brandThemeId = getArguments().getInt("brandThemeId", -1);
        dataBinder.setOnClickEvent(this);
        dataBinder.stateView.setContentView(dataBinder.flCOntainer);
        dataBinder.stateView.getRefreshView().setOnClickListener(this);
        dataBinder.stateView.getNetworkView().setOnClickListener(this);
        initBrandGoodsListView();//初始化品牌商品列表
    }

    @Override
    protected boolean isInitHttpCallback() {
        return false;
    }

    @Override
    public boolean isInitShowLoadingDialog() {
        return true;
    }

    // 初始化品牌商品列表
    @SuppressWarnings("unchecked")
    private void initBrandGoodsListView() {
        adapter = new TempleteAdapter(context, R.layout.griditem_brand_detail,
                new TempleteAdapter.OnInitAdapterListener<GriditemBrandDetailBinding, BrandDetailListInfoEntry>() {
                    @Override
                    public void initSetValue(GriditemBrandDetailBinding binder, BrandDetailListInfoEntry item, int position) {
                        ViewGroup.LayoutParams imgLayoutParams = binder.imgGoods.getLayoutParams();
                        imgLayoutParams.height = (int) (DeviceUtil.getScreenWidth(context) - DensityUtil.dip2px(context, 21.0f)) / 2;
                        binder.imgGoods.setLayoutParams(imgLayoutParams);
                        binder.setItem(item);
                    }
                });
        dataBinder.gvGoods.setNumColumns(2);
//        dataBinder.gvGoods.setColumnSpacing((int) DensityUtil.px2dip(context, 10), (int) DensityUtil.px2dip(context, 10));
        dataBinder.gvGoods.setAdapter(adapter);
        dataBinder.gvGoods.setOnRefreshListener(this);
        dataBinder.gvGoods.setOnItemClickListener(this);
        GoodsScrollListener goodsScrollListener = new GoodsScrollListener(this);
        goodsScrollListener.setOnScrollDirectionChangedListener(new GoodsScrollListener.OnScrollDirectionChangedListener() {
            @Override
            public void onScrollDirectionChanged(GoodsScrollListener.Direction direction) {
                EventBus.getDefault().post(new BrandDetailGoodsListViewScrollStateChangedEvent(direction));
            }
        });
        dataBinder.gvGoods.setOnScrollListener(goodsScrollListener);
    }

    /**
     * 排序方法
     **/
    public void setSortState(int sort, int mode) {
        String sortState = getCurrentSortState(sort, mode);
        if (!sortState.equals(this.sortState))
            this.sortState = sortState;
        if (!isHadLoaded) {
            loadGoodsData(); // 加载商品
        } else {
            if((sort == BrandSortView.SORT_PRICE && sortMode != mode)
                    || (sort == BrandSortView.SORT_SALE_COUNT && sortMode != mode)){
                currentPage = 0;//标识页码为0
                httpCallback = null;//使之产生加载对话框
                loadGoodsData(); // 加载商品
            }
        }
        this.sort = sort;
        this.sortMode = mode;
    }

    /**
     * 获取当前的排序状态
     **/
    @SuppressWarnings("unchecked")
    public static String getCurrentSortState(int sort, int mode) {
        switch (sort) {
            case BrandSortView.SORT_DEFAULT:
                return "default";
            case BrandSortView.SORT_NEW:
                break;
            case BrandSortView.SORT_SALE_COUNT:
                return mode == BrandSortView.MODE_B2S ? "volume_desc" : "volume_asc";
            case BrandSortView.SORT_PRICE:
                return mode == BrandSortView.MODE_B2S ? "price_desc" : "price_asc";
        }
        return "";
    }

    @Override
    public void onScrollIdle() {
        imageLoader.resume();
    }

    @Override
    public void onScrollFling() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTouchScroll() {
        imageLoader.pause();
    }

    @Override
    public void onScrollTopPositiont() {
        // 判断滚动到顶部
        if (dataBinder.img2Top.getVisibility() == View.VISIBLE) {
            dataBinder.img2Top.setVisibility(View.GONE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2HideAnimation());
        }
    }

    @Override
    public void onScrollFirstLastPosition() {
        onScrollLastPosition();
//         第一次滚动至底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
    }

    @Override
    public void onScrollLastPosition() {
        // 判断滚动到底部
        if (dataBinder.img2Top.getVisibility() == View.GONE) {
            dataBinder.img2Top.setVisibility(View.VISIBLE);
            dataBinder.img2Top.startAnimation(AnimationUtil.getGo2TopButton2ShowAnimation());
        }
        if (currentPage + 1 <= pageCount) {
            loadGoodsData();//加载商品数据
        } else {
//            Toast.show(context, "已经到底了!");
            dataBinder.gvGoods.onRefreshComplete();
        }
    }

    @Override
    public void onResume() {
        if (adapter != null)//刷新页面数据
            adapter.notifyDataSetChanged();
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl://刷新事件
            case R.id.network_error_ll://网络错误事件
                loadGoodsData();
                break;
            case R.id.img2Top://去顶部
                dataBinder.gvGoods.setSelection(0); // 到顶部
                onScrollTopPositiont();//执行滚动到顶部隐藏的动画
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BrandDetailListInfoEntry item = (BrandDetailListInfoEntry)dataBinder.gvGoods.getItemAtPosition(position);
        AppHelper.startGoodsDetailPageByBrandGoodsId(activity, item.title, Long.parseLong(item.item_id), 2);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        currentPage = 0;//页码默认为0
        loadGoodsData();//加载商品数据
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        if (currentPage + 1 > pageCount) {
            Toast.show(context, "已经到底了!");
            dataBinder.gvGoods.onRefreshComplete();
            return;
        }
        loadGoodsData();//加载商品数据
    }

    /**
     * 加载商品数据
     **/
    private void loadGoodsData() {
        Map<String, String> params = new HashMap<>();
        params.put("id", String.valueOf(brandThemeId));
        params.put("sort", sortState); //default:默认 price_desc:价格降序 price_asc:价格升序 volume_desc:销量降序 volume_asc:销量升序
        params.put("page", String.valueOf(++currentPage));
        if (httpCallback == null) {
            isHadLoaded = true;
            initHttpCall();
        }
        HttpClient.post(Url.toRoute(Url.ExtUrl.BrandDetailList, 1), params, httpCallback);
    }

    @Override
    public void onLoadHttpDataSuccessful(JsonData json) {
        super.onLoadHttpDataSuccessful(json);
        dataBinder.gvGoods.onRefreshComplete();
        if (json.optInt("status") == 200) {
            JsonData json_data = json.optJson("data");
            try {
                JsonData json_page = json_data.optJson("page");
                currentPage = json_page.optInt("page");
                pageCount = json_page.optInt("page_size");
                //设置页面数据
                List<BrandDetailListInfoEntry> goods = new Gson().fromJson(
                        json_data.optJson("item").toString(),
                        new TypeToken<ArrayList<BrandDetailListInfoEntry>>() {
                        }.getType()
                );
                if (goods != null && goods.size() > 0) {
                    if (currentPage == 1) {//重置加载，清空数据
                        adapter.clear();
                    }
                    adapter.addItem(goods);
                    adapter.syncDataSource();
                }
                dataBinder.stateView.setRefreshVisibility(View.GONE);
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
            currentPage--;
            Toast.show(context, getResources().getString(R.string.pull_to_refresh_nodata));
        } else {
            currentPage--;
            Toast.show(context, json.optString("info"));
        }
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onLoadHttpDataFaield(FailData data) {
        super.onLoadHttpDataFaield(data);
        dataBinder.gvGoods.onRefreshComplete();
        if (currentPage > 0) currentPage--; //页码最小不能小于0，大于0的情况下，如果未加载成功，页面需要还原
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }


}
